package com.jlf.starter.redis.reactive.context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.jlf.tool.gson.adapter.LocalDateAdapter;
import com.jlf.tool.gson.adapter.LocalDateTimeAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 基于gson的序列化反序列化工具
 *
 * @author wujr
 * 2023/8/4
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/8/4 1.0 新增]
 */
public class GsonRedisSerializer<T> implements RedisSerializer<T> {
    static final byte[] EMPTY_ARRAY = new byte[0];
    private static final Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
            .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
            .create();
    @Override
    public byte[] serialize(Object source) throws SerializationException {
        if (source == null) {
            return EMPTY_ARRAY;
        }

        return gson.toJson(source).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    @SuppressWarnings("unchecked")
    public T deserialize(byte[] bytes) throws SerializationException {
        if (null == bytes || bytes.length <= 0) {
            return null;
        }
        String jsonString = new String(bytes, StandardCharsets.UTF_8);
        return (T)JsonParser.parseString(jsonString);
    }
}
